package com.tuanzi.loan.business.repository.family.impl;

import com.tuanzi.loan.business.repository.family.UpdateVersionRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.vo.request.family.UpdateVersionSearchRequest;
import com.tuanzi.loan.vo.response.family.UpdateVersionSearchResponse;
import com.tuanzi.loan.vo.view.family.UpdateVersionView;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jooq.*;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.util.List;

import static com.tuanzi.loan.generated.jooq.loan.Tables.*;

@Repository
public class UpdateVersionRepositoryImpl extends JOOQBaseRepositoryPlus implements UpdateVersionRepository {

	@Override
	protected TableImpl getTable() {
		return APP_UPDATE_VERSION;
	}

	@Override
	public Page<UpdateVersionSearchResponse> list(UpdateVersionSearchRequest searchRequest, Pageable pageable) {
		SelectJoinStep<Record5<Integer, String, Byte, String, Byte>> base = dslContext
				.select(APP_UPDATE_VERSION.ID, APP_UPDATE_VERSION.VERSION_NO, APP_UPDATE_VERSION.UPDATE_TYPE, APP_UPDATE_VERSION.CONTENT, APP_UPDATE_VERSION.STATUS)
				.from(APP_UPDATE_VERSION);

		StringBuilder sb = new StringBuilder();

		if (StringUtils.isNotEmpty(searchRequest.getVersionNo())) {
			sb.append(String.format("AND VERSION_NO=%s ", searchRequest.getVersionNo()));
		}

		if (searchRequest.getUpdateType() != null) {
			sb.append(String.format("AND UPDATE_TYPE=%s ", searchRequest.getUpdateType()));
		}

		if (CollectionUtils.isNotEmpty(searchRequest.getProductIdList())) {
			sb.append(String.format("AND EXISTS (SELECT 1 from product_update_version WHERE auv_id = app_update_version.id AND prd_id IN (%s)) ", searchRequest.getProductIdList().toArray()));
		}

		Result<Record5<Integer, String, Byte, String, Byte>> fetch = null;
		if (StringUtils.isEmpty(sb)) {
			fetch = base.orderBy(APP_UPDATE_VERSION.VERSION_NO.desc()).limit(pageable.getPageSize()).offset(pageable.getOffset()).fetch();
		} else {
			fetch = base.where(sb.substring("AND".length(), sb.length())).orderBy(APP_UPDATE_VERSION.VERSION_NO.desc()).limit(pageable.getPageSize()).offset(pageable.getOffset()).fetch();
		}

		return new PageImpl<>(fetch.map((RecordMapper<Record, UpdateVersionSearchResponse>) record -> {
			UpdateVersionSearchResponse response = new UpdateVersionSearchResponse();
			Integer id = record.get(APP_UPDATE_VERSION.ID);
			response.setId(id);
			response.setVersionNo(record.get(APP_UPDATE_VERSION.VERSION_NO));
			response.setUpdateType(record.get(APP_UPDATE_VERSION.UPDATE_TYPE).intValue() == 0 ? "非强制" : "强制");
			String content = record.get(APP_UPDATE_VERSION.CONTENT);
			response.setContent(content.length() > 15 ? content.substring(0, 15) + "……" : content);
			response.setStatus(record.get(APP_UPDATE_VERSION.STATUS).intValue() == 0 ? "未上线" : "已上线");

			String[] productNames = dslContext.select(COMM_PRODUCT_PRDID.NAME)
					.from(PRODUCT_UPDATE_VERSION)
					.leftJoin(COMM_PRODUCT_PRDID).on(COMM_PRODUCT_PRDID.PRDID.eq(PRODUCT_UPDATE_VERSION.PRD_ID))
					.where(PRODUCT_UPDATE_VERSION.AUV_ID.eq(id)).fetchInto(String.class).toArray(new String[0]);

			response.setProductNames(StringUtils.join(productNames, "、"));
			return response;
		}));
	}

	@Override
	public void updateStatus(Integer id, int status) {
		dslContext.update(APP_UPDATE_VERSION).set(APP_UPDATE_VERSION.STATUS, (byte) status).where(APP_UPDATE_VERSION.ID.eq(id)).execute();
		dslContext.update(PRODUCT_UPDATE_VERSION).set(PRODUCT_UPDATE_VERSION.STATUS, (byte) status).where(PRODUCT_UPDATE_VERSION.AUV_ID.eq(id)).execute();
	}

	@Override
	public UpdateVersionView findById(Integer id) {
		UpdateVersionView view = dslContext.select(APP_UPDATE_VERSION.ID, APP_UPDATE_VERSION.VERSION_NO, APP_UPDATE_VERSION.UPDATE_TYPE, APP_UPDATE_VERSION.CONTENT, APP_UPDATE_VERSION.IS_CORNER_ICON_SHOW, APP_UPDATE_VERSION.STATUS)
				.from(APP_UPDATE_VERSION).where(APP_UPDATE_VERSION.ID.eq(id)).fetchOneInto(UpdateVersionView.class);

		List<String> prdIds = dslContext.select(COMM_PRODUCT_PRDID.PRDID)
				.from(PRODUCT_UPDATE_VERSION)
				.leftJoin(COMM_PRODUCT_PRDID).on(COMM_PRODUCT_PRDID.PRDID.eq(PRODUCT_UPDATE_VERSION.PRD_ID))
				.where(PRODUCT_UPDATE_VERSION.AUV_ID.eq(id)).fetchInto(String.class);

		view.setPrdIds(prdIds);

		return view;
	}

	@Override
	public UpdateVersionView save(UpdateVersionView view) {
		dslContext.delete(PRODUCT_UPDATE_VERSION).where(PRODUCT_UPDATE_VERSION.AUV_ID.eq(view.getId())).execute();

		for (String prdId : view.getPrdIds()) {
			dslContext.insertInto(PRODUCT_UPDATE_VERSION,
					PRODUCT_UPDATE_VERSION.AUV_ID, PRODUCT_UPDATE_VERSION.PRD_ID, PRODUCT_UPDATE_VERSION.STATUS)
					.values(view.getId(), Integer.valueOf(prdId), view.getStatus()).execute();
		}

		return view;
	}
}
